using B.S.RbacData.ErrorCode;
using ContentmanagementBase.Domain.Enums;
using ContentmanagementBaseRead.API.Applications.Commands.Popularizations;
using ContentmanagementBaseRead.API.Dtos;
using MediatR;
using System.ComponentModel;
using System.Reflection;

namespace ContentmanagementBaseRead.API.Applications.Commandhandlters.Popularizations
{
    /// <summary>
    /// 获取科室疾病类型对应关系命令处理器
    /// </summary>
    public class GetDepartmentDiseaseTypesCommandHandler : IRequestHandler<GetDepartmentDiseaseTypesCommand, ApiResult<List<DepartmentDiseaseTypeDto>>>
    {
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<GetDepartmentDiseaseTypesCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        public GetDepartmentDiseaseTypesCommandHandler(ILogger<GetDepartmentDiseaseTypesCommandHandler> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 处理获取科室疾病类型对应关系命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<ApiResult<List<DepartmentDiseaseTypeDto>>> Handle(GetDepartmentDiseaseTypesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理获取科室疾病类型对应关系命令");

                var result = new List<DepartmentDiseaseTypeDto>();

                // 获取所有科室
                var departments = GetMedicalDepartments();
                
                // 获取所有疾病类型
                var diseaseTypes = GetDiseaseTypes();

                // 按科室分组疾病类型
                foreach (var department in departments)
                {
                    var departmentDiseaseTypes = diseaseTypes
                        .Where(dt => dt.DepartmentId == department.Value)
                        .ToList();

                    result.Add(new DepartmentDiseaseTypeDto
                    {
                        Department = department,
                        DiseaseTypes = departmentDiseaseTypes
                    });
                }

                _logger.LogInformation("科室疾病类型对应关系获取成功，共 {Count} 个科室", result.Count);

                return new ApiResult<List<DepartmentDiseaseTypeDto>>
                {
                    code = ResultEnumCode.Ok,
                    message = "科室疾病类型对应关系获取成功",
                    data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取科室疾病类型对应关系过程中发生异常");
                return new ApiResult<List<DepartmentDiseaseTypeDto>>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取科室疾病类型对应关系异常：{ex.Message}",
                    data = new List<DepartmentDiseaseTypeDto>()
                };
            }
        }

        /// <summary>
        /// 获取医疗科室列表
        /// </summary>
        /// <returns>医疗科室列表</returns>
        private List<MedicalDepartmentDto> GetMedicalDepartments()
        {
            var departments = new List<MedicalDepartmentDto>();

            var enumType = typeof(MedicalDepartmentEnum);
            var enumValues = Enum.GetValues(enumType);

            foreach (var enumValue in enumValues)
            {
                var value = (int)enumValue;
                var name = enumValue.ToString();
                
                var fieldInfo = enumType.GetField(name);
                var descriptionAttribute = fieldInfo?.GetCustomAttribute<DescriptionAttribute>();
                var description = descriptionAttribute?.Description ?? name;

                departments.Add(new MedicalDepartmentDto
                {
                    Value = value,
                    Name = name,
                    Description = description
                });
            }

            return departments;
        }

        /// <summary>
        /// 获取疾病类型列表
        /// </summary>
        /// <returns>疾病类型列表</returns>
        private List<DiseaseTypeDto> GetDiseaseTypes()
        {
            var diseaseTypes = new List<DiseaseTypeDto>();

            var enumType = typeof(DiseaseTypeEnum);
            var enumValues = Enum.GetValues(enumType);

            foreach (var enumValue in enumValues)
            {
                var value = (int)enumValue;
                var name = enumValue.ToString();
                
                var fieldInfo = enumType.GetField(name);
                var descriptionAttribute = fieldInfo?.GetCustomAttribute<DescriptionAttribute>();
                var description = descriptionAttribute?.Description ?? name;

                var departmentId = GetDepartmentIdByDiseaseType(value);

                diseaseTypes.Add(new DiseaseTypeDto
                {
                    Value = value,
                    Name = name,
                    Description = description,
                    DepartmentId = departmentId
                });
            }

            return diseaseTypes;
        }

        /// <summary>
        /// 根据疾病类型获取对应的科室ID
        /// </summary>
        /// <param name="diseaseType">疾病类型值</param>
        /// <returns>科室ID</returns>
        private int GetDepartmentIdByDiseaseType(int diseaseType)
        {
            return diseaseType switch
            {
                // 内科疾病
                1 => (int)MedicalDepartmentEnum.内科, // 冠心病
                2 => (int)MedicalDepartmentEnum.内科, // 高血压
                3 => (int)MedicalDepartmentEnum.内科, // 心律失常
                4 => (int)MedicalDepartmentEnum.内科, // 糖尿病
                5 => (int)MedicalDepartmentEnum.内科, // 房颤

                // 外科疾病
                6 => (int)MedicalDepartmentEnum.外科, // 胆结石
                7 => (int)MedicalDepartmentEnum.外科, // 痔
                8 => (int)MedicalDepartmentEnum.外科, // 胰腺炎

                // 妇产科疾病
                9 => (int)MedicalDepartmentEnum.妇产科, // 乳腺炎

                // 儿科疾病
                10 => (int)MedicalDepartmentEnum.儿科, // 小儿肺炎
                11 => (int)MedicalDepartmentEnum.儿科, // 小儿哮喘
                12 => (int)MedicalDepartmentEnum.儿科, // 小儿咳嗽
                13 => (int)MedicalDepartmentEnum.儿科, // 小儿感冒

                // 其他疾病
                0 => (int)MedicalDepartmentEnum.未分类, // 未分类
                99 => (int)MedicalDepartmentEnum.其他, // 其他

                // 默认归类为其他
                _ => (int)MedicalDepartmentEnum.其他
            };
        }
    }
} 